package edu.neusoft.yuejian_09.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import edu.neusoft.yuejian_09.R;
import edu.neusoft.yuejian_09.base.Constant;
import edu.neusoft.yuejian_09.base.RetrofitListener;
import edu.neusoft.yuejian_09.bean.Train;
import edu.neusoft.yuejian_09.model.TrainModel;
import it.sephiroth.android.library.picasso.Picasso;

import static edu.neusoft.yuejian_09.base.Constant.PHOTO_URL;

public class TrainInfoActivity extends Activity implements RetrofitListener<Train> {

    private TextView t_name,t_intro,t_address,t_time,t_price,t_ask,t_enroll;
    private ImageView img_collect,img_return,t_pic;

    private int train_id;
    private String train_name;
    private String train_intro;
    private Object train_time;
    private String train_address;
    private int train_price;
    private int train_phone;
    private String train_pic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.activity_train_info);
        initViews();
        initEvents();
        initData();
    }

    public void initViews(){
        t_name=(TextView)findViewById(R.id.trainname);
        t_intro=(TextView)findViewById(R.id.traininfo);
        t_address=(TextView)findViewById(R.id.trainaddress);
        t_time=(TextView)findViewById(R.id.traintime);
        t_price=(TextView)findViewById(R.id.trainprice);
        t_ask=(TextView)findViewById(R.id.trainask);
        t_enroll=(TextView)findViewById(R.id.trainenroll);
        img_collect=(ImageView)findViewById(R.id.img_collect);
        img_return=(ImageView)findViewById(R.id.img_return);
        t_pic=(ImageView)findViewById(R.id.trainpic);
    }

    public void initEvents(){
        img_return.setOnClickListener(new View.OnClickListener() {//返回
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        t_enroll.setOnClickListener(new View.OnClickListener(){//购买跳转
            @Override
            public void onClick(View v){
                Intent intent = new Intent(TrainInfoActivity.this, EnrollTrainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("train_name",train_name);
                bundle.putInt("train_price",train_price);
                bundle.putInt("train_id",train_id);
                bundle.putString("train_intro",train_intro);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        t_ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查是否获得了权限（Android6.0运行时权限）
                if (ContextCompat.checkSelfPermission(TrainInfoActivity.this,
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
                    // 没有获得授权，申请授权
                    if (ActivityCompat.shouldShowRequestPermissionRationale(TrainInfoActivity.this,
                            Manifest.permission.CALL_PHONE)) {
                        // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                        // 弹窗需要解释为何需要该权限，再次请求授权
                        Toast.makeText(TrainInfoActivity.this, "请授权！", Toast.LENGTH_LONG).show();

                        // 帮跳转到该应用的设置界面，让用户手动授权
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);
                    }else{
                        // 不需要解释为何需要该权限，直接请求授权
                        ActivityCompat.requestPermissions(TrainInfoActivity.this,
                                new String[]{Manifest.permission.CALL_PHONE},
                                Constant.MY_PERMISSIONS_REQUEST_CALL_PHONE);
                    }
                }else {
                    // 已经获得授权，可以打电话
                    CallPhone();
                }
            }
        });

    }

    private void CallPhone() {
        String number = Integer.toString(train_phone);
        if (TextUtils.isEmpty(number)) {
            // 提醒用户
            // 注意：在这个匿名内部类中如果用this则表示是View.OnClickListener类的对象，
            // 所以必须用MainActivity.this来指定上下文环境。
            Toast.makeText(TrainInfoActivity.this, "号码不能为空！", Toast.LENGTH_SHORT).show();
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
    }

    // 处理权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode){
            case Constant.MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    CallPhone();
                } else {
                    // 授权失败！
                    Toast.makeText(this, "授权失败！", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }

    public void initData(){

        getTrainInfo();

    }

    //获取活动信息数据
    public void getTrainInfo(){

        Bundle bundle = getIntent().getExtras();
        train_id = bundle.getInt("train_id");
        TrainModel trainModel = new TrainModel();
        trainModel.getTrainById(train_id,this);

    }
    @Override
    public void onSuccess(Train train,int flag){
        train_name = train.getTrain_name();
        train_price = train.getTrain_price();
        train_pic =PHOTO_URL+train.getTrain_pic();
        train_intro=train.getTrain_intro();
        train_address=train.getTrain_address();
        train_time=train.getTrain_time();
        train_phone=train.getTrain_phone();
        t_name.setText(train_name);
        t_price.setText("￥" + train_price);
        t_intro.setText(train_intro);
        t_address.setText(train_address);
        t_time.setText(train_time+"");
        //t_phone.setText(train_phone+"");
        if (train_pic != "") {
            Picasso.with(TrainInfoActivity.this)
                    .load(train_pic)
                    .into(t_pic);
            t_pic.setScaleType(ImageView.ScaleType.FIT_XY);
        } else {
            t_pic.setImageResource(R.drawable.no_pic);
        }

    }
    @Override
    public void onFail(){ Toast.makeText(TrainInfoActivity.this, "网络发生错误", Toast.LENGTH_SHORT).show();}

}
